#include "CaptureDevice.h"

BEGIN_DIRECTSHOWWRAPPER_NAMESPACE

CaptureDevice::CaptureDevice(const IMonikerPtr& pMoniker) :
	m_pBaseFilter(NULL),
	m_pMonikerPtr(pMoniker),
	m_pPropertyBagPtr(NULL)
{
	//_ASSERT(pMoniker);

	HRESULT hr;
	hr = m_pMonikerPtr->BindToStorage(0, 
									  0, 
									  IID_IPropertyBag, 
									  (void **)&m_pPropertyBagPtr);
	if(FAILED(hr))
	{
		throw _com_error(hr);
	}
}

CaptureDevice::~CaptureDevice()
{
	if(m_pBaseFilter != NULL)
	{
		m_pBaseFilter->Release();
		m_pBaseFilter.Detach();
	}

	if(m_pPropertyBagPtr != NULL)
	{
		m_pPropertyBagPtr->Release();
		m_pPropertyBagPtr.Detach();
	}

	if(m_pMonikerPtr != NULL)
	{
		m_pMonikerPtr->Release();
		m_pMonikerPtr.Detach();
	}
}

IBaseFilterPtr CaptureDevice::BindDeviceFilter() const
{
	if(m_pBaseFilter == NULL)
	{
		HRESULT hr;
		hr = m_pMonikerPtr->BindToObject(NULL, 
			   							 NULL, 
										 IID_IBaseFilter,
										(void **)&m_pBaseFilter);
		if(SUCCEEDED(hr))
		{
			//hr = CoCreateInstance(CLSID_SampleGrabber, 
			//					  NULL, 
			//					  CLSCTX_INPROC_SERVER,
			//					  IID_IBaseFilter, 
			//					 (void**)&m_pSampleGrabber);
			

			return m_pBaseFilter;
		}
	}

	return m_pBaseFilter;
}

const _bstr_t CaptureDevice::GetName() const
{
	VARIANT varName;
	VariantInit(&varName);
	
	HRESULT hr = m_pPropertyBagPtr->Read(L"FriendlyName", &varName, 0);
	return _bstr_t(varName);

}

END_DIRECTSHOWWRAPPER_NAMESPACE